package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.service.IPermissionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RequestMappingHandlerMapping rmhm;


    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    public void role() {

    }

    public List<Permission> selectByRoleId(Long id) {
        return permissionMapper.selectByRoleId(id);
    }

    public void reload() {
        List<String> resources = permissionMapper.selectAllResource();

        Collection<HandlerMethod> methods = rmhm.getHandlerMethods().values();
        for (HandlerMethod method : methods) {
            RequiresPermissions anno = method.getMethodAnnotation(RequiresPermissions.class);
            if(anno!=null){
                String resource = anno.value()[0];
                if(!resources.contains(resource)){
                    Permission p = new Permission();
                    p.setName(anno.value()[1]);
                    p.setResource(anno.value()[0]);
                    permissionMapper.insert(p);
                }
            }
        }
    }


    public Collection<String> selectResourceByEmpId(Long empId) {
        return permissionMapper.selectResourceByEmpId(empId);
    }

}
